﻿using System;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Foundation.MarkupExtensions
{
    /// <summary>
    /// Picture Manager.
    /// </summary>
    public class PictureManager : ResourceManager
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PictureManager"/> class.
        /// </summary>
        /// <param name="basePath">The base path.</param>
        public PictureManager(string basePath)
            : this(Assembly.GetCallingAssembly(), basePath)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PictureManager"/> class.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <param name="basePath">The base path.</param>
        public PictureManager(Assembly assembly, string basePath)
        {
            BasePath = basePath.Replace('\\', '/');
            BasePath = BasePath.StartsWith("/") ? BasePath.Substring(1) : BasePath; 
            ResourceAssemblyName = assembly.GetName().Name;
            ResourceAssembly = assembly;
        }

        /// <summary>
        /// Gets the path.
        /// </summary>
        public string BasePath { get; private set; }

        /// <summary>
        /// Gets the resource assembly.
        /// </summary>
        public Assembly ResourceAssembly { get; private set; }
        
        private string ResourceAssemblyName { get; set; }

        /// <summary>
        /// Gets the object.
        /// </summary>
        /// <param name="key">The path.</param>
        /// <returns></returns>
        public override object GetObject(string key)
        {
            try
            {
                key = Path.Combine(BasePath, key).Replace('\\', '/');
                if (!ResourceHelper.ResourceExists(ResourceAssembly, key)) return null;
                key = key.StartsWith("/") || key.StartsWith("component") ? key : "/" + key;
                key = key.StartsWith("component") ? ";" + key : ";component" + key;
                var uri = new Uri("pack://application:,,,/" + ResourceAssemblyName + key);
                var image = new BitmapImage(uri);
                return new Image {Source = image};
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
